package com.toe.order.webapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.toe.commodity.service.CommodityGoodsService;
import com.toe.commodity.service.CommodityGoodsSpecificationsService;
import com.toe.common.exception.NoRollbackForToeServiceException;
import com.toe.common.exception.ToeServiceException;
import com.toe.common.restful.StateEnum;
import com.toe.common.utils.TimeUtil;
import com.toe.order.service.OrderCartService;
import com.toe.order.webapi.mapper.OrderCartMapper;

import com.toe.pojo.dto.order.AddOrderCartDTO;
import com.toe.pojo.entity.order.OrderCart;
import com.toe.pojo.vo.commodity.CommodityGoodsSpecificationsVO;
import com.toe.pojo.vo.commodity.CommodityOrderGoodsVO;
import com.toe.pojo.vo.order.OrderCartSimpleVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陶涛
 * @since 2022-07-19
 */
@Service
@Transactional(noRollbackFor = NoRollbackForToeServiceException.class)
public class OrderCartServiceImpl extends ServiceImpl<OrderCartMapper, OrderCart> implements OrderCartService {

    @DubboReference
    private CommodityGoodsService dubboCommodityGoodsService;

    @DubboReference
    private CommodityGoodsSpecificationsService dubboCommodityGoodsSpecificationsService;

    @Autowired
    private OrderCartMapper orderCartMapper;

    /**
     * 加入购物车
     * @param orderCartDTO
     */
    @Override
    public void addNewCart(AddOrderCartDTO orderCartDTO) {
        QueryWrapper<OrderCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", orderCartDTO.getUserId())
                .eq("goods_id", orderCartDTO.getGoodsId())
                .eq("specifications_id", orderCartDTO.getSpecificationsId())
                .eq("is_delete", 0);
        OrderCart queryResult = orderCartMapper.selectOne(wrapper);
        if (queryResult == null) {
            OrderCart orderCart = new OrderCart();
            BeanUtils.copyProperties(orderCartDTO, orderCart);
            orderCart.setIsDelete(0);
            Date now = TimeUtil.localDateTimeToDate(LocalDateTime.now());
            orderCart.setCreateTime(now);
            orderCart.setUpdateTime(now);

            int rows = orderCartMapper.insert(orderCart);
            if (rows == 0) {
                throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                        "加入购物车失败,请稍后重试");
            }
        } else {
            int newCount = orderCartDTO.getCount()+queryResult.getCount();
            updateCountById(
                    orderCartDTO.getUserId(),
                    queryResult.getId(),
                    newCount
            );
        }
    }

    /**
     * 删除购物车中的商品
     * @param cartId
     */
    @Override
    public List<OrderCartSimpleVO> deleteById(Long userId, Long cartId) {
        int rows = orderCartMapper.deleteById(cartId);
        if (rows == 0) {
            throw new ToeServiceException(StateEnum.ERR_ORDER_EMPTY,
                    "该商品已经移出购物车");
        }

        return getOrderCartSimpleByUserId(userId);
    }

    /**
     * 购物车中商品购买数量加一
     * @param cartId
     */
    @Override
    public List<OrderCartSimpleVO> countPlusOneById(Long userId, Long cartId) {
        int rows = orderCartMapper.countPlusOneById(cartId);
        if (rows == 0) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "商品数量添加失败,请稍后重试");
        }

        return getOrderCartSimpleByUserId(userId);
    }

    /**
     * 购物车中商品购买数量减一
     * @param cartId
     */
//    @Override
//    public OrderCartVO countMinusOneById(Long userId, Long cartId) {
//        int rows = orderCartMapper.countMinusOneById(cartId);
//        if (rows == 0) {
//            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
//                    "商品数量减少失败,请稍后重试");
//        }
//
//        return getOrderCartSimpleByUserId(userId);
//    }

    @Override
    public void countMinusOneById(Long userId, Long cartId) {
        int rows = orderCartMapper.countMinusOneById(cartId);
        if (rows == 0) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "商品数量减少失败,请稍后重试");
        }
    }

    /**
     * 修改购物车中商品的购买数量
     * @param cartId
     * @param newCount
     */
    @Override
    public List<OrderCartSimpleVO> updateCountById(Long userId, Long cartId, Integer newCount) {
        OrderCart orderCart = new OrderCart();
        orderCart.setId(cartId);
        orderCart.setCount(newCount);

        int rows = orderCartMapper.updateById(orderCart);
        if (rows == 0) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "商品数量修改失败,请稍后重试");
        }

        return getOrderCartSimpleByUserId(userId);
    }

    /**
     * 修改购物车中商品的购买规格
     * @param cartId
     * @param specificationsId
     */
    @Override
    public List<OrderCartSimpleVO> updateSpecificationsById(Long userId, Long cartId, Long specificationsId) {
        OrderCart orderCart = new OrderCart();
        orderCart.setId(cartId);
        orderCart.setSpecificationsId(specificationsId);

        int rows = orderCartMapper.updateById(orderCart);
        if (rows == 0) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "商品规格修改失败,请稍后重试");
        }

        return getOrderCartSimpleByUserId(userId);
    }

//    /**
//     * 得到该用户的购物车列表
//     * @param userId
//     * @return
//     */
//    @Override
//    public OrderCartVO getOrderCartSimpleByUserId(Long userId) {
//        QueryWrapper<OrderCart> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_id", userId)
//                .eq("is_delete", 0);
//
//        List<OrderCart> orderCarts = orderCartMapper.selectList(wrapper);
//        if (orderCarts == null) {
//            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
//                    "服务器忙,请稍后重试");
//        }
//
//        List<OrderCartSimpleVO> list = new ArrayList<>();
//        BigDecimal tolPrice = new BigDecimal("0");
//        for (OrderCart orderCart : orderCarts) {
//            CommodityOrderGoodsVO goods = dubboCommodityGoodsService
//                    .getOrderGoodsById(
//                            orderCart.getGoodsId(),
//                            orderCart.getSpecificationsId()
//                    );
//            System.out.println("goodsId: "+orderCart.getGoodsId());
//            System.out.println("specificationsId: "+orderCart.getSpecificationsId());
//            System.out.println("goods: "+goods);
//            OrderCartSimpleVO simpleVO = new OrderCartSimpleVO();
//            simpleVO.setId(orderCart.getId());
//            simpleVO.setTitle(goods.getTitle());
//            simpleVO.setCover(goods.getCover());
//            simpleVO.setSpecifications(goods.getSpecifications());
//            simpleVO.setPrice(goods.getPrice());
//            simpleVO.setType(goods.getTypeName());
//            simpleVO.setCount(orderCart.getCount());
//
//            list.add(simpleVO);
//
//            System.out.println("=======增加前tolPrice: "+tolPrice);
//            tolPrice = tolPrice.add(simpleVO.getPrice()
//                    .multiply(
//                            new BigDecimal(simpleVO.getCount())));
//            System.out.println("=======增加后tolPrice: "+tolPrice);
//            System.out.println("乘法: "+simpleVO.getPrice()
//                    .multiply(new BigDecimal(simpleVO.getCount())));
//        }
//
//        OrderCartVO orderCartVO = new OrderCartVO();
//        orderCartVO.setList(list);
//        orderCartVO.setTolPrice(tolPrice);
//        System.out.println("tolPrice: "+tolPrice);
//
//        return orderCartVO;
//    }

    /**
     * 得到该用户的购物车列表
     * @param userId
     * @return
     */
    @Override
    public List<OrderCartSimpleVO> getOrderCartSimpleByUserId(Long userId) {
        QueryWrapper<OrderCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("is_delete", 0);

        List<OrderCart> orderCarts = orderCartMapper.selectList(wrapper);
        if (orderCarts == null) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "服务器忙,请稍后重试");
        }

        List<OrderCartSimpleVO> list = new ArrayList<>();
        for (OrderCart orderCart : orderCarts) {
            CommodityOrderGoodsVO goods = dubboCommodityGoodsService
                    .getOrderGoodsById(
                            orderCart.getGoodsId(),
                            orderCart.getSpecificationsId()
                    );
            OrderCartSimpleVO simpleVO = new OrderCartSimpleVO();
            simpleVO.setId(orderCart.getId());
            simpleVO.setTitle(goods.getTitle());
            simpleVO.setCover(goods.getCover());
            simpleVO.setSpec(goods.getSpecifications());
            simpleVO.setPrice(goods.getPrice());
            simpleVO.setType(goods.getTypeName());
            simpleVO.setCount(orderCart.getCount());

            List<CommodityGoodsSpecificationsVO> specificationsList =
                    dubboCommodityGoodsSpecificationsService
                            .getSpecificationsList(orderCart.getGoodsId());
            simpleVO.setSpecList(specificationsList);

            list.add(simpleVO);
        }

        return list;
    }

    /**
     * 计算已选择商品的总价格
     * @param cartIds
     * @return
     */
    @Override
    public BigDecimal getTolPrice(Long[] cartIds) {
        QueryWrapper<OrderCart> wrapper = new QueryWrapper<>();
        for (int i = 0; i < cartIds.length; i++) {
            if (i == 0) {
                wrapper.eq("id", cartIds[i]);
            } else {
                wrapper.or()
                        .eq("id", cartIds[i]);
            }
        }
        List<OrderCart> orderCarts = orderCartMapper.selectList(wrapper);
        if (orderCarts == null) {
            throw new ToeServiceException(StateEnum.ERR_SERVER_ERROR,
                    "服务器忙,请稍后重试");
        }

        BigDecimal tolPrice = new BigDecimal("0");
        for (OrderCart orderCart : orderCarts) {
            CommodityOrderGoodsVO goods = dubboCommodityGoodsService
                    .getOrderGoodsById(
                            orderCart.getGoodsId(),
                            orderCart.getSpecificationsId()
                    );
            System.out.println("=======增加前tolPrice: "+tolPrice);
            tolPrice = tolPrice.add(goods.getPrice()
                    .multiply(
                            new BigDecimal(orderCart.getCount())));
            System.out.println("=======增加后tolPrice: "+tolPrice);
            System.out.println("乘法: "+goods.getPrice()
                    .multiply(new BigDecimal(orderCart.getCount())));
        }

        return tolPrice;
    }

}
